package cc.messcat.web.filter;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.util.BeanUtil;
import cc.messcat.entity.area.Area;
import cc.messcat.entity.level.UserLevel;
import cc.messcat.entity.system.McUser;
import cc.messcat.service.area.AreaService;
import cc.messcat.util.LevelUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class UserLoginCheckFilter extends HandlerInterceptorAdapter {

    @Autowired
    private AreaService areaService;

    private final Map<Long, Long> map = new ConcurrentHashMap<>();

    /**
     * 会员登录拦截器,拦截除少数无需登录的接口以判断会员是否登录,如会员未登录拦截请求并回复相应提示
     *
     * @param request  从请求中获取memberID
     * @param response 如会员未登录则回复提示信息:800未传用户ID,801用户ID不合法,802未找到用户,803用户未登录
     * @return true为会员正常登录, false为未登录
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession();
        McUser user = (McUser) request.getSession().getAttribute("user");
        if (!BeanUtil.isValid(user)) {
            if (LevelUtil.isAjaxRequest(request))
                responseJson(response);
            else
                rediectUrl(request,response);
            return false;
        }
        //未审核可以通过
        if(!"未审核".equals(user.getCheckState())){
        	Long areaId = user.getAreaId();
        	UserLevel userLevel = user.getUserLevel();
        	int level = userLevel.getLevel();
        	
        	if (0 == userLevel.getLevel()) {
        		level++;
        	}
       
	        if (null == session.getAttribute("area" + (level))) {
	            Area area0;
	            if (0L == areaId) {
	                area0 = areaService.findAreasByParentId(areaId).get(0);
	            } else {
	                area0 = areaService.getByAreaID(areaId);
	            }
	
	
	            List<Area> areas = new ArrayList<>();
	            areas.add(area0);
	            List<Area> areas1 = new ArrayList<>();
	            areas1.add(area0);
	            session.setAttribute("area" + level, areas);
	            System.out.println("***************area" + level + ":" + areas1.size());
	            while (level < 5) {
	                List<Area> areas3 = new ArrayList<>();
	                for (Area a : areas1) {
	                    List<Area> areas2 = areaService.findAreasByParentId(a.getId());
	                    areas3.addAll(areas2);
	                }
	                session.setAttribute("area" + (level + 1), areas3);
	                areas1.clear();
	                areas1.addAll(areas3);
	                level++;
	                System.out.println("***************area" + level + ":" + areas3.size());
	            }
	            areas1.clear();
	        }
        }
        return true;
    }

    private void responseJson(HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        map.put("message", "登录超时!");
        map.put("status", 301);
        //将实体对象转换为JSON Object转换
        String jsonString = JSONObject.toJSONString(map);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    private void rediectUrl(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.sendRedirect(request.getContextPath() + "/login");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
